<template>
  <div class="usersList">
   <el-row>
    <el-col :span="3">
      <el-button type="success" @click="addUserDialog = true">添加用户</el-button>
    </el-col>
    <el-col :span="10">
      <el-input
      v-model="pageInfo.query"
      placeholder="搜索用户"
      @input="getUsersList" />
    </el-col>
   </el-row>
   <!-- 表格列表 -->
   <el-table :data="tableData" style="width: 100%">
    <el-table-column type="index" label="序号" width="60" />
    <el-table-column prop="id" label="ID" width="80" />
    <el-table-column prop="username" label="用户名" width="100" />
    <el-table-column prop="role_name" label="角色名称" width="120" />
    <el-table-column prop="email" label="邮箱" width="160" />
    <el-table-column label="状态" width="80">
      <template #default="{ row }">
        <el-switch
          v-model="row.mg_state"
          @change="statusHandler(row)"
          class="ml-2"
          style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
        />
      </template>
    </el-table-column>
    <el-table-column prop="mobile" label="电话" width="150" />
    <el-table-column label="操作" width="150">
      <template #default="{ row }">
        <el-tooltip
          class="box-item"
          effect="dark"
          content="编辑"
          placement="left-start"
        >
        <el-button type="primary" :icon="'User'" circle @click="editUserHandler(row)"/>
        </el-tooltip>
        <el-tooltip
          class="box-item"
          effect="dark"
          content="分配角色"
          placement="top"
        >
          <el-button type="success" :icon="'Check'" circle @click="roleHandler(row)" />
        </el-tooltip>

        <el-popconfirm title="真的要删除这个用户吗？" @confirm="delteHandler(row.id)">
          <template #reference>
            <el-button type="danger" :icon="'Delete'" circle />
          </template>
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>

  <hr>
  <!-- 分页器 -->
    <div class="demo-pagination-block">
      <el-pagination
        :hide-on-single-page="true"
        v-model:current-page="pageInfo.pagenum"
        v-model:page-size="pageInfo.pagesize"
        :page-sizes="[2, 4, 6, 8]"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageInfo.total"
        @size-change="getUsersList"
        @current-change="getUsersList"
      />
    </div>

  <!-- 添加用户对话框 -->
  <el-dialog v-model="addUserDialog" title="添加用户">
    <el-form
      :model="adduser"
      label-width='80px'
      :rules="rules"
      ref="formRef"
     >
        <el-form-item label="用户名：" prop="username">
          <el-input v-model="adduser.username" type="text"/>
        </el-form-item>
        <el-form-item label="密码：" prop="password">
          <el-input v-model="adduser.password" type="text"/>
        </el-form-item>
        <el-form-item label="邮箱：" prop="email">
          <el-input v-model="adduser.email" type="email"/>
        </el-form-item>
        <el-form-item label="电话：" prop="mobile">
          <el-input v-model="adduser.mobile" type="text"/>
        </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="resetHandler">重置</el-button>
        <el-button type="primary" @click="addUserHandler">确认添加</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 编辑用户对话框 -->
  <el-dialog v-model="editUserDialog" title="编辑用户">
    <el-form
    :model="editInfo"
    label-width='100px'
    ref="formRef"
    >
      <el-form-item label="用户名：" prop="username">
        <el-input v-model="editInfo.username" type="text" disabled />
      </el-form-item>
      <el-form-item label="电话号：" prop="mobile">
        <el-input v-model="editInfo.mobile" type="text" />
      </el-form-item>
      <el-form-item label="邮箱：" prop="email">
        <el-input v-model="editInfo.email" type="text" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="editUserDialog=false">取消</el-button>
        <el-button type="primary" @click="editHandler">确认编辑</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 分配角色对话框 -->
  <el-dialog v-model="roletUserDialog" title="分配角色">
    <el-form
    :model="roleInfo"
    label-width='100px'
    ref="formRef"
    >
      <el-form-item label="用户名：" prop="username">
        <el-input v-model="roleInfo.username" type="text" disabled />
      </el-form-item>
      <el-form-item label="分配角色：" prop="role_name">
        <el-select v-model="roleInfo.rid" class="m-2" placeholder="Select">
          <el-option
          v-for="item in roleoptions"
          :key="item.id"
          :label="item.roleName"
          :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="roletUserDialog = false">取消</el-button>
        <el-button type="primary" @click="roleconfirmHandler">确认分配角色</el-button>
      </span>
    </template>
  </el-dialog>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus'
export default {
  name: 'oaUsers',
  data () {
    return {
      input: '',
      tableData: [],
      pageInfo: {
        pagenum: 1,
        pagesize: 2,
        total: 200,
        query: ''
      },
      addUserDialog: false,
      adduser: {},
      rules: {
        username: [
          { required: true, message: '请输入用户名!', trigger: 'change' },
          { min: 5, max: 12, message: '用户名请输入5-12位!', trigger: 'change' }
        ],
        password: [
          { required: true, message: '请输入密码!', trigger: 'change' },
          { min: 5, max: 12, message: '密码请输入5-12位!', trigger: 'change' }
        ]
      },
      editUserDialog: false,
      editInfo: {},
      roletUserDialog: false,
      roleInfo: {},
      roleoptions: []
    }
  },
  methods: {
    async getUsersList () {
      const res = await this.$http.get('users', { params: this.pageInfo })
      if (res.meta?.status !== 200) return
      this.tableData = res.data.users
      this.pageInfo.total = res.data.total
    },
    // 修改用户状态
    async statusHandler (userInfo) {
      const res = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
      if (res.meta?.status !== 200) return
      ElMessage({
        showClose: true,
        message: '用户状态修改成功！',
        type: 'success'
      })
    },
    // 添加用户对话框确认按钮
    addUserHandler () {
      this.$refs.formRef.validate(async valid => {
        if (!valid) {
          ElMessage({
            showClose: true,
            message: '请正确添加用户信息！',
            type: 'error'
          })
          return
        }

        const res = await this.$http.post('users', this.adduser)
        if (res.meta?.status === 400) {
          ElMessage({
            showClose: true,
            message: res.meta.msg
          })
          return
        }

        if (res.meta?.status === 201) {
          ElMessage({
            showClose: true,
            message: '添加用户成功！',
            type: 'success'
          })
        }
        this.addUserDialog = false
        this.adduser = {}
        this.getUsersList()
      })
    },
    // 重置按钮
    resetHandler () {
      this.$refs.formRef.resetFields()
    },
    // 删除用户
    async delteHandler (id) {
      const res = await this.$http.delete(`users/${id}`)
      if (res.meta?.status !== 200) return
      ElMessage({
        showClose: true,
        message: '删除用户成功！',
        type: 'success'
      })
      this.getUsersList()
    },
    // 分配角色对话框
    async roleHandler (info) {
      const res = await this.$http.get('roles')

      this.roleInfo.username = info.username
      this.roleInfo.id = info.id

      if (res.meta?.status !== 200) return
      this.roleoptions = res.data
      const role = res.data.find(item => item.roleName === info.role_name)
      this.roleInfo.rid = role?.id
      this.roletUserDialog = true
    },
    // 确定分配角色按钮
    async roleconfirmHandler () {
      const res = await this.$http.put(`users/${this.roleInfo.id}/role`, { rid: this.roleInfo.rid })
      if (res.meta.status !== 200) return

      ElMessage({
        showClose: true,
        message: '角色分配成功！',
        type: 'success'
      })
      this.roletUserDialog = false
      this.getUsersList()
    },
    // 编辑用户对话框
    async editUserHandler (info) {
      this.editInfo.username = info.username
      this.editInfo.mobile = info.mobile
      this.editInfo.email = info.email
      this.editInfo.id = info.id

      this.editUserDialog = true
    },
    // 确定编辑按钮
    async editHandler () {
      const res = await this.$http.put(`users/${this.editInfo.id}`, { email: this.editInfo.email, mobile: this.editInfo.mobile })

      if (res.meta?.status !== 200) return
      ElMessage({
        showClose: true,
        message: '编辑成功！',
        type: 'success'
      })

      this.editUserDialog = false
      this.getUsersList()
    }
  },
  created () {
    this.getUsersList()
  }
}
</script>

<style scoped lang="scss"></style>
